package com.starlink.common.scheduled;

import com.starlink.mapper.StarPaintMapper;
import com.starlink.model.domain.StarPaintDO;
import com.starlink.model.domain.StarPaintRegisterDO;
import com.starlink.model.request.PointsAcquireBillRequest;
import com.starlink.service.PointsService;
import com.starlink.service.StarPaintRegisterService;
import com.starlink.service.StarPaintService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import static com.starlink.common.enums.ActionTypeEum.JOIN_STAR_PAINT_ACTIVITY;

@Component
public class StarPaintTask {

    @Autowired
    private StarPaintMapper starPaintMapper;
    @Autowired
    private StarPaintService starPaintService;
    @Autowired
    private StarPaintRegisterService starPaintRegisterService;
    @Autowired
    private PointsService pointsService;

    @Scheduled(cron = "0 */1 * * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void dealStarPaintFinish() {
        // 查询已经
        List<StarPaintDO> starPaintDOS = starPaintMapper.queryList();
        if (CollectionUtils.isEmpty(starPaintDOS)) {
            return;
        }

        for (StarPaintDO starPaintDO : starPaintDOS) {
            // 查询报名记录
            List<StarPaintRegisterDO> list = starPaintRegisterService.lambdaQuery()
                    .eq(StarPaintRegisterDO::getStarPaintId, starPaintDO.getId())
                    .list();
            for (StarPaintRegisterDO starPaintRegisterDO : list) {
                PointsAcquireBillRequest billRequest = new PointsAcquireBillRequest();
                billRequest.setUserId(starPaintRegisterDO.getUserId());
                billRequest.setTitle(JOIN_STAR_PAINT_ACTIVITY.getType());
                billRequest.setAcquireMode(JOIN_STAR_PAINT_ACTIVITY.getType());
                billRequest.setAcquirePoint(starPaintDO.getObtainPoints());
                pointsService.addPoint(billRequest);
            }
            starPaintDO.setStatus(0);
            starPaintDO.setObtainFlag(1);
            starPaintDO.setManualOff(1);
            starPaintService.saveOrUpdate(starPaintDO);
        }
    }
}
